package com.heima.behavior.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.behavior.service.ReadBehaviorService;
import com.heima.common.constants.BehaviorConstants;
import com.heima.common.constants.HotArticleConstants;
import com.heima.common.redis.CacheService;
import com.heima.model.behavior.dtos.ReadBehaviorDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.mess.UpdateArticleMess;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.thread.ApUserThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
public class ReadBehaviorServiceImpl implements ReadBehaviorService {
    @Autowired
    private CacheService cacheService;

    @Autowired
    private KafkaTemplate<String, String> kafkaTemplate;


    /**
     * 处理用户阅读行为
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult handlerReadBehavior(ReadBehaviorDto dto) {
        //1.入参校验
        if (dto == null || dto.getArticleId() == null || dto.getCount() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.判断用户是否登录
        ApUser apUser = ApUserThreadLocalUtil.getUser();
        if (apUser == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

//        //TODO 发送kafka消息,增加文章阅读数
//        Map map = new HashMap();
//        map.put("articleId", dto.getArticleId());
//        map.put("type", "read");
//        map.put("count", dto.getCount());
//        kafkaTemplate.send(BehaviorConstants.USER_BEHAVIOR_TOPIC, JSON.toJSONString(map));
        log.info("行为微服务-阅读行为 发送kafka消息用于流式计算ok....");

        //3.查询redis中是否有记录,如果有记录更新阅读数
        String jsonStr = (String) cacheService.hGet(BehaviorConstants.READ_BEHAVIOR + dto.getArticleId(),
                apUser.getId().toString());
        if (StringUtils.isNotEmpty(jsonStr)) {
            //redis中已经存在该用户对于该篇文章的阅读记录, 需要累加阅读次数
            ReadBehaviorDto readBehaviorDto = JSON.parseObject(jsonStr, ReadBehaviorDto.class);
            dto.setCount(readBehaviorDto.getCount() + dto.getCount());
        }
        //更新/保存redis记录
        cacheService.hPut(BehaviorConstants.READ_BEHAVIOR + dto.getArticleId(),
                apUser.getId().toString(),
                JSON.toJSONString(dto));

        log.info("redis中用户对于文章{}的阅读次数更新ok...", dto.getArticleId());


        ////发送kafka消息用于文章分值流式计算
        UpdateArticleMess mess = new UpdateArticleMess();
        mess.setArticleId(dto.getArticleId());
        mess.setType(UpdateArticleMess.UpdateArticleType.VIEWS);
        mess.setAdd(1);
        kafkaTemplate.send(HotArticleConstants.HOT_ARTICLE_SCORE_TOPIC, JSON.toJSONString(mess));


        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
